package com.mindainfo.configCenter.config.service.impl;

import com.mindainfo.configCenter.base.common.DataGrid;
import com.mindainfo.configCenter.base.common.Response;
import com.mindainfo.configCenter.base.common.ResponseFactory;
import com.mindainfo.configCenter.base.utils.JSONUtil;
import com.mindainfo.configCenter.config.bean.RemoteConfig;
import com.mindainfo.configCenter.config.dao.IRemoteConfigDao;
import com.mindainfo.configCenter.config.service.IConfigService;
import com.mindainfo.configCenter.config.vo.RemoteConfigEditVo;
import com.mindainfo.configCenter.config.vo.RemoteConfigPageVo;
import com.mindainfo.configCenter.config.vo.RemoteConfigVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by MD-01 on 2016/11/16.
 */
@Service
public class ConfigServiceImpl implements IConfigService{


    private Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);
    @Resource
    private IRemoteConfigDao configDao;
    /**
     * 保存配置信息
     */
    public Response<Void> save(RemoteConfig config){

        //id为空,添加.先判断是否存在相同的ip
        if(config.getId()==null){
            RemoteConfig remoteConfig = configDao.getByServerHost(config.getServerHost());
            if(remoteConfig!=null){
                return ResponseFactory.error("已经存在该ip的配置,请不要重复添加");
            }
            config.setUsable(true);
        }else{
            String id = config.getId().toString();
            if(configDao.get(id)==null){
                return ResponseFactory.error("错误的配置编号");
            }
        }
        configDao.save(config);
        return ResponseFactory.ok();
    }

    /**
     * 根据服务器ip获取配置信息
     */
    public Response<RemoteConfigVo> getConfig(String serverHost){

        if(StringUtils.isEmpty(serverHost)){
            return ResponseFactory.error("服务器ip不能为空");
        }
        RemoteConfig remoteConfig = configDao.getByServerHost(serverHost);
        if(remoteConfig==null){
            return ResponseFactory.error("该服务器还没有配置信息");
        }
        if(!remoteConfig.isUsable()){
            return ResponseFactory.error("该配置已经被禁用");
        }

        remoteConfig.getVisitDates().add(new Date());
        configDao.save(remoteConfig);

        RemoteConfigVo vo = new RemoteConfigVo();
        try {
            BeanUtils.copyProperties(vo,remoteConfig);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(JSONUtil.toJson(remoteConfig));
        return ResponseFactory.ok(vo);
    }

    /**
     * 页面上查询配置信息列表
     */
    public DataGrid<RemoteConfigPageVo> queryList(String keyword, String page, String rows){

        if(StringUtils.isEmpty(page)){
            page = "1";
        }
        if(StringUtils.isEmpty(rows)){
            rows = "10";
        }
        int iPage = Integer.parseInt(page);
        int num = Integer.parseInt(rows);
        int start = (iPage-1)*num;



        List<RemoteConfig> configs = configDao.queryList(keyword,start,num);
        int count = configDao.queryListCount(keyword);
        List<RemoteConfigPageVo> vos = new ArrayList<>();
        FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd HH:mm");
        for(RemoteConfig config : configs){
            RemoteConfigPageVo vo = new RemoteConfigPageVo();
            vo.setId(config.getId().toString());
            vo.setCreateTime(fdf.format(config.getCreateTime()));
            vo.setServerHost(config.getServerHost());
            vo.setServerName(config.getServerName());
            if(config.isUsable()){
                vo.setUsable("可用");
            }else{
                vo.setUsable("不可用");
            }
            vos.add(vo);
        }
        DataGrid<RemoteConfigPageVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setCount(count);
        logger.info(JSONUtil.toJson(dataGrid));
        return dataGrid;
    }

    /**
     * 根据id查询
     */
    public Response<RemoteConfigEditVo> queryById(String id){

        RemoteConfig remoteConfig = configDao.get(id);
        if(remoteConfig==null){
            return ResponseFactory.error("错误的id");
        }
        RemoteConfigEditVo vo = new RemoteConfigEditVo();
        try {
            BeanUtils.copyProperties(vo,remoteConfig);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        vo.setId(id);
        return ResponseFactory.ok(vo);
    }

}
